import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getKeyList, useDark } from "@pureadmin/utils";
import {
  getOperationLogsList,
  batchDeleteOperationLogs,
  clearOperationLogs
} from "@/api/system";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, computed } from "vue";

import { getFilter } from "@/utils/filter";

export function useRole(tableRef: Ref) {
  const form = reactive({
    username: "",
    auth: "",
    createtime: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 当前网页是否为`dark`模式 请求方法style
  const { isDark } = useDark();
  const methodStyle = computed(() => {
    return (action: string) => {
      let style = {};
      switch (action) {
        case "POST":
          style = {
            "--el-tag-text-color": isDark.value ? "#6abe39" : "#389e0d",
            "--el-tag-bg-color": isDark.value ? "#172412" : "#f6ffed",
            "--el-tag-border-color": isDark.value ? "#274a17" : "#b7eb8f"
          };
          break;
        case "GET":
          style = {
            "--el-tag-text-color": isDark.value ? "#e84749" : "#cf1322",
            "--el-tag-bg-color": isDark.value ? "#2b1316" : "#fff1f0",
            "--el-tag-border-color": isDark.value ? "#58191c" : "#ffa39e"
          };
          break;
        case "PUT":
          style = {
            "--el-tag-text-color": isDark.value ? "#f9c700" : "#fadb14",
            "--el-tag-bg-color": isDark.value ? "#3b3b3b" : "#fffbe6",
            "--el-tag-border-color": isDark.value ? "#595959" : "#ffe58f"
          };
          break;
        case "DELETE":
          style = {
            "--el-tag-text-color": isDark.value ? "#096dd9" : "#096dd9",
            "--el-tag-bg-color": isDark.value ? "#122b40" : "#e6f7ff",
            "--el-tag-border-color": isDark.value ? "#1d39c4" : "#91d5ff"
          };
          break;
        default:
          style = {
            "--el-tag-text-color": isDark.value ? "#6abe39" : "#389e0d",
            "--el-tag-bg-color": isDark.value ? "#172412" : "#f6ffed",
            "--el-tag-border-color": isDark.value ? "#274a17" : "#b7eb8f"
          };
      }
      return style;
    };
  });

  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "序号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "操作人员",
      prop: "username",
      minWidth: 100
    },
    {
      label: "请求方法",
      prop: "action",
      minWidth: 140,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={methodStyle.value(row.action)}>
          {row.action}
        </el-tag>
      )
    },
    {
      label: "操作标识",
      prop: "auth",
      minWidth: 140
    },
    {
      label: "操作 IP",
      prop: "ip_address",
      minWidth: 100
    },
    {
      label: "路径",
      prop: "path",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "os",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "browser",
      minWidth: 100
    },
    {
      label: "操作时间",
      prop: "createtime",
      minWidth: 180,
      formatter: ({ createtime }) =>
        dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = parseInt(val as any);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    batchDeleteOperationLogs(getKeyList(curSelected, "id")).then(res => {
      if (res.code) {
        message("已删除选中数据", {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      } else {
        message(res.msg, {
          type: "error"
        });
      }
    });
  }

  /** 清空日志 */
  function clearAll() {
    // 根据实际业务，调用接口删除所有日志数据
    clearOperationLogs().then(res => {
      if (res.code) {
        message("已删除所有日志数据", {
          type: "success"
        });
        onSearch();
      } else {
        message(res.msg, {
          type: "error"
        });
      }
    });
  }

  async function onSearch() {
    loading.value = true;

    let filter = await getFilter(form);

    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "desc"
    };

    const { data } = await getOperationLogsList(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    clearAll,
    resetForm,
    onbatchDel,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
